require('reflect-metadata');
const { config } = require('dotenv');
const { DataSource } = require('typeorm');

module.exports = async function globalSetup() {
  console.log('🔧 设置全局测试环境...');

  // 加载测试环境变量
  config({ path: '.env.test' });

  // 设置测试环境变量
  process.env.NODE_ENV = 'test';
  process.env.DB_NAME = process.env.DB_NAME || 'weubi_crawler_test';
  process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-jwt-secret';
  process.env.JWT_REFRESH_SECRET = process.env.JWT_REFRESH_SECRET || 'test-jwt-refresh-secret';

  // 统一使用 @weubi/shared 导入实体类
  const { User, CrawlerTask, CrawledData } = require('@weubi/shared');

  console.log('✅ 实体类导入成功');

  // 创建全局测试数据库连接
  const testDataSource = new DataSource({
    type: 'postgres',
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT || '5433'),
    username: process.env.DB_USER || 'crawler',
    password: process.env.DB_PASSWORD || '123qwe',
    database: process.env.DB_NAME || 'weubi_crawler_test',
    synchronize: true, // 测试环境自动同步表结构
    logging: false, // 测试时关闭日志
    entities: [User, CrawlerTask, CrawledData],
    dropSchema: false, // 不要删除schema
  });

  try {
    await testDataSource.initialize();
    console.log('✅ 测试数据库连接成功');
    
    // 将数据源保存到全局变量
    global.__TEST_DATA_SOURCE__ = testDataSource;
    
    // 设置全局测试数据库配置
    global.__TEST_DB_CONFIG__ = {
      type: 'postgres',
      host: process.env.DB_HOST || 'localhost',
      port: parseInt(process.env.DB_PORT || '5433'),
      username: process.env.DB_USER || 'crawler',
      password: process.env.DB_PASSWORD || '123qwe',
      database: process.env.DB_NAME || 'weubi_crawler_test',
      synchronize: false, // 已经初始化过了，不需要再同步
      logging: false,
      entities: [User, CrawlerTask, CrawledData],
      dropSchema: false,
    };
    
  } catch (error) {
    console.error('❌ 测试数据库连接失败:', error);
    throw error;
  }
};
